package com.thm.tfast.modules.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thm.tfast.core.enums.DeleteFlagEnum;
import com.thm.tfast.core.exception.Asserts;
import com.thm.tfast.core.sevruity.domain.SysUserDetails;
import com.thm.tfast.core.utils.SecurityUtil;
import com.thm.tfast.modules.sys.mapper.SysMenuMapper;
import com.thm.tfast.modules.sys.model.SysMenu;
import com.thm.tfast.modules.sys.model.SysRoleMenu;
import com.thm.tfast.modules.sys.model.dto.menu.MenuInsertDto;
import com.thm.tfast.modules.sys.model.dto.menu.MenuUpdateDto;
import com.thm.tfast.modules.sys.model.vo.menu.MenuVo;
import com.thm.tfast.modules.sys.service.SysCacheService;
import com.thm.tfast.modules.sys.service.SysMenuService;
import com.thm.tfast.modules.sys.service.SysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 菜单信息 服务实现类
 * </p>
 *
 * @author THM
 * @since 2022-10-10
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    private SysCacheService sysCacheService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public List<MenuVo> getMenusByUserId(Long userId) {
        List<SysMenu> menus = this.baseMapper.getMenusByUserId(userId);
        return BeanUtil.copyToList(menus,MenuVo.class);
    }

    @Override
    public Page<SysMenu> page(String keyword, Long parentId, Integer pageNum, Integer pageSize) {
        Page<SysMenu> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysMenu> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotEmpty(keyword)) {
            wrapper.like(SysMenu::getTitle, keyword);
        }
        if (Objects.nonNull(parentId)){
            wrapper.eq(SysMenu::getParentId,parentId);
        }
        wrapper.ne(SysMenu::getDelFlag,DeleteFlagEnum.DELETED.getCode());
        return this.page(page, wrapper);
    }

    @Override
    @Transactional
    public Long insert(MenuInsertDto dto) {
        SysMenu sysMenu = this.getOne(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getTitle, dto.getTitle()));
        if (Objects.nonNull(sysMenu)){
            Asserts.fail("菜单名称已经存在");
        }
        sysMenu = BeanUtil.toBean(dto, SysMenu.class);
        if (Objects.nonNull(sysMenu.getParentId())){
            SysMenu parentMenu = this.getById(sysMenu.getParentId());
            if (Objects.isNull(parentMenu)){
                Asserts.fail("父级菜单不存在");
            }
            //设置层级为  父级菜单的下一级
            sysMenu.setLevel(parentMenu.getLevel() + 1);
        }
        SysUserDetails currentUser = SecurityUtil.getCurrentUser();
        sysMenu.setCreateUser(currentUser.getUserId());
        sysMenu.setCreateTime(currentUser.getDate());
        sysMenu.setUpdateUser(currentUser.getUserId());
        sysMenu.setUpdateTime(currentUser.getDate());
        this.save(sysMenu);
        return sysMenu.getId();
    }

    @Override
    @Transactional
    public Boolean update(MenuUpdateDto dto) {
        if (Objects.isNull(this.getById(dto.getId()))){
            Asserts.fail("菜单信息不存在");
        }
        SysMenu sysMenu = BeanUtil.toBean(dto, SysMenu.class);
        SysUserDetails currentUser = SecurityUtil.getCurrentUser();
        sysMenu.setUpdateUser(currentUser.getUserId());
        sysMenu.setUpdateTime(currentUser.getDate());
        //删除与菜单相关缓存
        delMenuCache(dto.getId());
        return this.updateById(sysMenu);
    }

    @Override
    @Transactional
    public Boolean delete(Long menuId) {
        SysMenu sysMenu = this.getById(menuId);
        if (Objects.isNull(sysMenu)){
            Asserts.fail("菜单信息不存在");
        }
        SysUserDetails currentUser = SecurityUtil.getCurrentUser();
        sysMenu.setUpdateUser(currentUser.getUserId());
        sysMenu.setUpdateTime(currentUser.getDate());
        sysMenu.setDelFlag(DeleteFlagEnum.DELETED.getCode());
        //删除与菜单相关缓存
        delMenuCache(menuId);
        return this.updateById(sysMenu);
    }

    /**
     * 删除角色相关用户菜单缓存
     * @param menuId 菜单ID
     */
    private void delMenuCache(Long menuId){
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.list(Wrappers
                .<SysRoleMenu>lambdaQuery()
                .eq(SysRoleMenu::getMenuId, menuId));
        if (CollectionUtil.isNotEmpty(sysRoleMenus)){
            sysRoleMenus.forEach(sysRoleMenu -> sysCacheService.delMenuByRoleId(sysRoleMenu.getRoleId()));
        }
    }
}
